package com.legal.aid.app.service.impl;

import com.legal.aid.app.domain.vo.CommonUserVo;
import com.legal.aid.app.mapper.AppUserMapper;
import com.legal.aid.app.service.IAppUserService;
import com.legal.aid.common.core.domain.entity.CommonUser;
import com.legal.aid.system.service.ISysCommonUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class AppUserServiceImpl implements IAppUserService {
    @Autowired
    private ISysCommonUserService commonUserService;

    @Autowired
    private AppUserMapper appUserMapper;

    @Override
    public CommonUserVo getByUserId(String userId) {
        CommonUser commonUser = commonUserService.selectCommonUserById(Long.parseLong(userId));
        if (commonUser != null) {
            CommonUserVo userVo = new CommonUserVo();
            userVo.setId(commonUser.getId());
            userVo.setUserName(commonUser.getUserName());
            userVo.setRealName(commonUser.getRealName());
            userVo.setAvatar(commonUser.getAvatar());
            userVo.setPhoneNumber(commonUser.getPhoneNumber());
            userVo.setGender(commonUser.getGender());
            userVo.setIsLawyer(commonUser.getIsLawyer());
            return userVo;
        }
        return null;
    }

    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        CommonUser commonUser = new CommonUser();
        commonUser.setId(userId);
        commonUser.setAvatar(avatar);
        return commonUserService.updateCommonUser(commonUser);
    }

    @Override
    public Map<Long, CommonUserVo> listByIds(ArrayList<Long> userIds) {
        List<CommonUserVo> userVoList = appUserMapper.getUserVoByIds(userIds);

        // 处理空值情况
        if (userVoList == null || userVoList.isEmpty()) {
            return Collections.emptyMap();
        }

        // 将列表转换为 Map（键为用户ID）
        return userVoList.stream()
                .collect(Collectors.toMap(
                        CommonUserVo::getId,  // 键为用户ID
                        Function.identity(),  // 值为用户对象本身
                        (existing, replacement) -> existing  // 冲突处理：保留第一个出现的对象
                ));
    }
}
